//
//  NSString+category.m
//  deerkids
//
//  Created by 王昭的Mac Air on 2017/8/31.
//  Copyright © 2017年 wangzhao. All rights reserved.
//

#import "NSString+category.h"

@implementation NSString (category)

#pragma mark - 属性文字段落格式设置
- (NSAttributedString *)formatWithParagraph:(CGFloat)lineSpaceing fontSize:(CGFloat)fontSize textColor:(UIColor *)textColor
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpaceing;
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],
                            NSParagraphStyleAttributeName:paragraphStyle,
                            NSForegroundColorAttributeName:textColor
                            };
    return [[NSAttributedString alloc] initWithString:self attributes:attrs];
}

#pragma mark - 内容表情替换
- (NSMutableAttributedString *)expressionFormatReplace
{
    NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:self];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[表情[1-9][1-9]{0,1}\\]" options:0 error:nil];
    NSArray *matches = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
    int mIndex = 0;
    if (matches.count > 0) {
        for (NSTextCheckingResult *result in [matches objectEnumerator]) {

            NSRange range = [result range];
            NSString *subString = [self substringWithRange:range];
            NSString *index = [subString substringWithRange:NSMakeRange(3, subString.length-4)];

            NSTextAttachment *attchImage = [[NSTextAttachment alloc] init];
            // 表情图片
            attchImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://js.qzone.cc/v3/images/face/%@.gif?_t=20170203", index]]]];
            // 设置图片大小
            attchImage.bounds = CGRectMake(0, 0, 16, 16);
            NSAttributedString *stringImage = [NSAttributedString attributedStringWithAttachment:attchImage];
            if (mIndex > 0) {
                NSUInteger mLocation = (range.location - mIndex);
                NSRange mRange = {mLocation, range.length};
                [attriStr replaceCharactersInRange:mRange withAttributedString:stringImage];
            }else{
                 [attriStr replaceCharactersInRange:range withAttributedString:stringImage];
            }
                  mIndex += (range.length -1);
        }
    }
    return attriStr;
}


@end
